package cn.xinfei.xdecision.common.utils.util;

import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class IpUtil {
    public static final String LOCAL_HOST_IP = "127.0.0.1";
    private static String localHostIp = null;

    public static void main(String[] args) {
        System.out.println(getIpAddress());
    }

    public static String getIpAddress() {
        if (StringUtils.isNotEmpty(localHostIp)) {
            return localHostIp;
        }
        String hostAddress = LOCAL_HOST_IP;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            localHostIp = hostAddress;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hostAddress;
    }

    public static List<String> getIpAddressList() {
        List<String> list = new LinkedList<>();
        try {
            Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface network = (NetworkInterface) enumeration.nextElement();
                if (network.isVirtual() || !network.isUp()) {
                    continue;
                } else {
                    Enumeration addresses = network.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = (InetAddress) addresses.nextElement();
                        if (address != null && (address instanceof Inet4Address || address instanceof Inet6Address)) {
                            list.add(address.getHostAddress());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
